# coding=utf-8
import os
from flask import Flask
from flask_babel import Babel
from flask_login import LoginManager
from flask_openid import OpenID
from flask_sqlalchemy import SQLAlchemy
from flask_script import Manager
from livereload import Server
from config import basedir, ADMINS, MAIL_USERNAME, MAIL_PORT, MAIL_SERVER, MAIL_PASSWORD
from flask_mail import Mail
from momentjs import momentjs

application = Flask(__name__)
application.debug = True
application.config.from_object('config')  # 加载配置文件
application.jinja_env.globals['momentjs'] = momentjs

babel = Babel(application)

# 使用flask script的方式启动应用
# manager = Manager(application)

# 发生错误则发送邮件，使用开发服务器模拟邮件服务器
# python -m smtpd -n -c DebuggingServer localhost:25
if not application.debug:
    import logging
    from logging.handlers import SMTPHandler

    credentials = None
    if MAIL_USERNAME or MAIL_PASSWORD:
        credentials = (MAIL_USERNAME, MAIL_PASSWORD)
    mail_handler = SMTPHandler((MAIL_SERVER, MAIL_PORT), 'no-reply@' + MAIL_SERVER, ADMINS, 'microblog failure',
                               credentials)
    mail_handler.setLevel(logging.ERROR)
    application.logger.addHandler(mail_handler)

# 记录错误信息到日志文件
if not application.debug:
    import logging
    from logging.handlers import RotatingFileHandler

    file_handler = RotatingFileHandler('tmp/microblog.log', 'a', 1 * 1024 * 1024, 10)
    file_handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'))
    application.logger.setLevel(logging.INFO)
    file_handler.setLevel(logging.INFO)
    application.logger.addHandler(file_handler)
    application.logger.info('microblog startup')

mail = Mail(application)  # 使用app的配置进行加载
db = SQLAlchemy(application)  # 初始化数据库

login_manager = LoginManager()
login_manager.init_app(application)
login_manager.login_view = 'login'
login_manager.login_message = u'please login first to access this page!'
oid = OpenID(application, os.path.join(basedir, 'tmp'))

from app import views, models
